# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = self.reverse(head)

        dummy = ListNode(next=pre)
        cur = dummy
        while cur.next:
            if cur.next.val < cur.val:
                cur.next = cur.next.next
                continue
            cur = cur.next
        return self.reverse(dummy.next)

    def reverse(self, head):
        pre = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        return pre
